<template>
  <div class="details">
    <div class="forbid-height" v-if="soucre == 1" @click="forbidHit"></div>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
      <el-form-item label="banner图" prop="banner">
        <el-upload action="https://api-qingchuang.xmw1688.com/common/upload" :show-file-list="false"
          :on-success="handleAvatarSuccess">
          <div class="img">
            <img v-if="ruleForm.banner != '' && ruleForm.banner != null" :src="ruleForm.banner" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="跳转至" prop="radio">
        <div class="parallel">
          <el-radio v-model="ruleForm.radio" label="0" @input="radioInput">无跳转</el-radio>
          <el-radio v-model="ruleForm.radio" label="1" @input="radioInput">商品详情</el-radio>
          <el-radio v-model="ruleForm.radio" label="2" @input="radioInput">html链接</el-radio>
        </div>
      </el-form-item>

      <el-form-item label="" v-if="ruleForm.radio == '2'">
        <div class="parallel">
          <el-input style="width: 300px" v-model="ruleForm.html" placeholder="具体链接-html" clearable></el-input>
        </div>
      </el-form-item>

      <el-form-item label="" class="mission" v-if="ruleForm.radio == '1'">
        <div class="commodity">
          <div class="search" v-if="soucre != 1">
            <div class="input">
              <el-input v-model="commonValue" placeholder="商品名称" clearable></el-input>
            </div>
            <div class="input">
              <el-cascader v-model="commonCascaderValue" :options="commonCascaderOptions" :props="propsCascader"
                clearable @expand-change="commonCascaderChange"></el-cascader>
            </div>

            <div class="common-button" @click="searchHit">搜索</div>
            <div class="common-button" style="background: #999999" @click="replacementHit">
              重置
            </div>

            <div class="common-button" v-if="headerIndex == 1" @click="addHit" style="background: #2a82e4">
              新增商品
            </div>
          </div>

          <div class="table" v-loading="loading">
            <el-table :data="tableData" style="width: 100%" @sort-change="sortChange" border :header-cell-style="{
              color: '#333333',
              backgroundColor: '#f3f3f3',
            }" tooltip-effect="dark" ref="multipleTable" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="70"> </el-table-column>
              <el-table-column prop="goodName" label="商品名称" width="300">
              </el-table-column>
              <el-table-column prop="" label="商品图">
                <template slot-scope="scope">
                  <img class="imgs" :src="scope.row.goodIcon" alt="" />
                </template>
              </el-table-column>
              <el-table-column prop="goodOneClassifyName" label="商品分类">
              </el-table-column>
              <el-table-column prop="retailPrice" label="销售价（元）" sortable>
              </el-table-column>
              <el-table-column prop="costPrice" label="成交价" sortable>
              </el-table-column>
              <el-table-column prop="inventoryNum" label="库存" sortable>
              </el-table-column>
              <el-table-column prop="saleNum" label="真实销量" sortable>
              </el-table-column>
            </el-table>

            <div class="pagination">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background
                layout="prev, pager, next" :total="tableDataTotal" :current-page="page">
              </el-pagination>
            </div>
          </div>


        </div>
      </el-form-item>

      <el-form-item class="mission" v-if="soucre != 1">
        <div class="form-button">
          <div class="list" @click="addClose">取消</div>
          <div class="list" @click="addConfirm('ruleForm')">保存</div>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  commonAdvertisingListId,
  commonAdvertisingListAdd,
} from "@/api/common";

import {
  saveCommodityClassifyList,
  saveCommodityList,
} from "@/api/save";

var throttle = require("@/utils/throttle"); // 防抖

export default {
  data() {
    return {
      id: "",
      ruleForm: {
        banner: "",

        //------
        radio: "0",

        ///----------
        path: "",
        html: "",
      },
      rules: {
        banner: [
          { required: true, message: "请上传banner图", trigger: "blur" },
        ],
        radio: [
          { required: true, message: "请勾选对应的类型", trigger: "change" },
        ],
      },
      //------------------------
      headerIndex: 0,
      commonValue: "",
      commonCascaderOptions: [],
      commonCascaderValue: "",
      propsCascader: {
        value: "goodClassifyId",
        label: "goodClassifyName",
        children: "children",
        checkStrictly: true,
      },
      commonCascaderIndex: 0,
      //-------------
      page: 1,
      limit: 10,
      tableData: [],
      tableDataTotal: 0,
      loading: false,
      commonObj: {},
      multipleSelection: [],
      //--------------
      //---------
      soucre: null,
    };
  },
  created() {
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.commonAdvertisingListIdMet();
    } else {
      this.saveCommodityListMet();
    }

    if (this.$route.query.soucre) {
      this.soucre = this.$route.query.soucre;
    }

    //---------
    this.saveCommodityClassifyListMet();
  },
  methods: {
    commonAdvertisingListIdMet() {
      let params = this.id;

      commonAdvertisingListId(params).then((res) => {
        if (res.errorCode == null) {
          this.detailsObj = res.resultData;
          //------
          this.ruleForm.banner = res.resultData.bannerImage;
          this.ruleForm.radio = res.resultData.bannerProperty + "";


          if (res.resultData.bannerProperty == 2) {
            this.ruleForm.html = res.resultData.url;
          } else if (res.resultData.bannerProperty == 1) {
            // this.commonValue = res.resultData.otherId
          }
          this.saveCommodityListMet();

        }
      });
    },
    //----------------
    radioInput(e) {
      this.ruleForm.html = "";
    },
    //---------上传
    handleAvatarSuccess(res, file) {
      this.ruleForm.banner = res.resultData;
    },
    //-----------
    addClose() {
      this.$router.push({
        path: "/save/banner/banner-list",
      });
    },
    addConfirm: throttle.throttle(function (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            bannerId: this.id,
            bannerType: 3,
            bannerImage: this.ruleForm.banner,
            bannerProperty: this.ruleForm.radio,
            url: this.ruleForm.radio == 2 ? this.ruleForm.html : '',
            otherId: this.ruleForm.radio == 1 ? this.multipleSelection[0].goodId : '',
            // otherName: this.ruleForm.radio == 1 ? this.multipleSelection[0].taskName : '',
            // otherType: this.intersectionActive
          };

          console.log("普通修改", params);

          commonAdvertisingListAdd(params).then((res) => {
            if (res.errorCode == null) {
              if (this.id == "") {
                this.$message.success("新增banner成功！");
              } else {
                this.$message.success("编辑banner成功！");
              }

              setTimeout(() => {
                this.$router.push({
                  path: "/save/banner/banner-list",
                });
              }, 1000);
            }
          });
        } else {
          return false;
        }
      });
    }, 3000),
    //--
    forbidHit() {
      this.$message.error("当前详情页，禁止修改");
    },

    //---------------------------------------------------------------------------
    // 加载一级数据
    saveCommodityClassifyListMet() {
      let params = {
        goodClassifyType: 0,
        fatherId: "",
        pageSize: this.limit,
        pageNo: this.page,
      };

      saveCommodityClassifyList(params).then((res) => {
        if (res.errorCode == null) {
          res.resultData.goodClassifyList.forEach((item, index) => {
            item.children = [];
          });
          this.commonCascaderOptions = res.resultData.goodClassifyList;
        }
      });
    },
    commonCascaderChange(e) {
      this.loadCascaderData(e[0]);
    },
    // 动态加载级联数据
    loadCascaderData(id) {
      let params = {
        goodClassifyType: 0,
        fatherId: id,
      };

      saveCommodityClassifyList(params).then((res) => {
        if (res.errorCode == null) {
          let mockData = res.resultData.goodClassifyList;

          this.commonCascaderOptions.forEach((item, index) => {
            if (item.goodClassifyId == id) {
              item.children = mockData;
            }
          });
        }
      });
    },
    saveCommodityListMet() {
      let params = {
        bannerId: this.id,
        goodName: this.commonValue,
        goodClassifyId:
          this.commonCascaderValue[this.commonCascaderValue.length - 1],
        orderType: this.tabProp, // 排序字段 0无 1销售价 2销售数量 3创建时间
        orderBy: this.tabSort, // 排序类型 0正 1倒
        isStatus: 1,

        pageSize: this.limit,
        pageNo: this.page,
      };

      saveCommodityList(params).then((res) => {
        if (res.errorCode == null) {
          let array = [];

          res.resultData.goodList.forEach((item, index) => {
            item.retailPrice = Number(item.retailPrice / 100).toFixed(2);
            item.costPrice = Number(item.costPrice / 100).toFixed(2);


            if (item.isUse == 1) {
              array = item;
            }

          });

          this.tableData = res.resultData.goodList;
          this.tableDataTotal = res.resultData.totalNum;

          if (this.ruleForm.radio == 1) {
            let row = array;
            this.$nextTick(() => {
              this.$refs.multipleTable.toggleRowSelection(row);
            });
          }


          this.loading = false;
        }
      });
    },
    searchHit() {
      this.loading = true;
      this.page = 1;
      this.saveCommodityListMet();
    },
    replacementHit() {
      this.commonValue = "";
      this.commonCascaderValue = "";

      this.loading = true;
      this.page = 1;
      this.saveCommodityListMet();
    },
    //------------------------------------------------
    sortChange(column) {
      // 当前列的排序  ascending 升序 descending 降序
      console.log("获取对象", column);
      if (column.order == "ascending") {
        this.tabSort = 0;
      } else if (column.order == "descending") {
        this.tabSort = 1;
      } else {
        this.tabSort = 0;
      }

      // 当前点击列名
      this.tabProp =
        column.prop == "retailPrice"
          ? 1
          : column.prop == "costPrice"
            ? 2
            : column.prop == "inventoryNum"
              ? 3
              : column.prop == "saleNum"
                ? 4
                : 0;

      this.page = 1;
      this.loading = true;
      this.saveCommodityListMet();
    },
    handleSelectionChange(selectedRows) {
      if (selectedRows.length > 1) {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.toggleRowSelection(
          selectedRows[selectedRows.length - 1]
        );
      }

      this.multipleSelection = [selectedRows[selectedRows.length - 1]];
    },
    //---------
    handleSizeChange(val) {
      this.limit = val;
      this.loading = true;
      this.saveCommodityListMet();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.loading = true;
      this.saveCommodityListMet();
    },
  },
};
</script>

<style lang="less" scoped>
@import url("@/assets/css/common.less");
@import url("@/assets/css/delete.less");

.details {
  /deep/ .el-form-item__label {
    text-align: left;
  }

  position: relative;

  .forbid-height {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 10;
    display: flex;
  }

  .img {
    width: 180px;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #ccc;
    border-radius: 5px;

    img {
      width: 100%;
      height: 100%;
      border-radius: 5px;
    }
  }

  .parallel {
    display: flex;
    align-items: center;
    height: 40px;
  }

  .operation {
    display: flex;
    align-items: center;
    color: #2a82e4;

    .list {
      margin-right: 20px;
      cursor: pointer;
    }
  }

  .mission {
    /deep/ .el-form-item__content {
      margin-left: 0 !important;
    }




    .form-button {
      display: flex;
      align-items: center;
      margin-top: 100px;
      margin-left: 120px;

      /deep/ .el-form-item__content {
        line-height: 0;
      }

      /deep/ .el-form-item__content {
        margin-left: 120px !important;
      }

      .list {
        background: #3da8f5;
        color: #fff;
        font-size: 16px;
        margin-right: 20px;
        border-radius: 5px;
        width: 80px;
        height: 35px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }

      .list:first-child {
        z-index: 11;
        position: relative;
      }

      .list:first-child {
        background: #808080;
      }
    }
  }


  .commodity {
    .common {
      .header {
        width: 100%;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #ccc;

        .list {
          width: 150px;
          height: 35px;
          background: #999999;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
          cursor: pointer;
        }

        .active {
          background: #2a82e4;
        }
      }
    }

    .search {
      display: flex;
      align-items: center;

      .input {
        margin-right: 10px;

        /deep/ .el-input {
          width: 250px;
        }
      }

      .common-button {
        padding: 0px 20px;
        box-sizing: border-box;
        border-radius: 5px;
        background: #2a82e4;
        font-size: 14px;
        color: #fff;
        margin-left: 20px;
        cursor: pointer;
      }

      .common-button:last-child {
        background: #999999;
      }
    }

    .table {
      margin-top: 10px;
    }
  }
}
</style>